﻿using Microsoft.AspNetCore.Mvc;
using ShenNius.Auth.API.Controllers;
using ShenNius.Auth.API.Infrastructure.Configs;
using ShenNius.Mall.API.Domain.Entity;
using ShenNius.Mall.API.Dtos.Input;
using ShenNius.Repository;
using SqlSugar;
using System;
using System.Threading.Tasks;

/*************************************
* 类名：AppUserController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/8/23 11:01:15
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Mall.API.Controllers
{
    /// <summary>
    /// 小程序用户地址
    /// </summary>
    public class AppUserAddressController : AppBaseController
    {

        private readonly IBaseRepository<AppUserAddress> _appUserAddressRepository;
        private readonly ISqlSugarClient _db;
        public AppUserAddressController(IBaseRepository<AppUserAddress> appUserAddressRepository, ISqlSugarClient db)
        {
            _appUserAddressRepository = appUserAddressRepository;
            _db = db;
        }

        private Tuple<string, string, string> GetNamesBySplitRegions(string regionName)
        {
            if (string.IsNullOrEmpty(regionName))
            {
                throw new ArgumentNullException("用户省市区为空!");
            }
            var regionsArry = regionName.Split(',', StringSplitOptions.RemoveEmptyEntries);
            return new Tuple<string, string, string>(regionsArry[0], regionsArry[1], regionsArry[2]);
        }
        [HttpGet]
        public async Task<ApiResult> Lists()
        {
            var addressList = await _appUserAddressRepository.GetListAsync(d => d.IsDeleted == false && d.AppUserId == HttpWx.AppUserId);
            return new ApiResult(addressList);
        }
        [HttpGet]
        public async Task<ApiResult> Detail(int addressId)
        {
            var addressModel = await _appUserAddressRepository.GetModelAsync(d => d.IsDeleted == false && d.AppUserId == HttpWx.AppUserId && d.Id.Equals(addressId));
            return new ApiResult(addressModel);
        }
        [HttpPost]
        public async Task<ApiResult> Add([FromForm] AddressInput input)
        {
            var tupleValue = GetNamesBySplitRegions(input.Region);
            var createModel = AppUserAddress.Create(HttpWx.AppUserId, input.Name, input.Detail, input.Phone, tupleValue.Item1, tupleValue.Item2, tupleValue.Item3);

            var sign = await _appUserAddressRepository.AddAsync(createModel);
            return Result(sign);
        }
        [HttpPost]
        public async Task<ApiResult> Edit([FromForm] AddressInput input)
        {
            var tupleValue = GetNamesBySplitRegions(input.Region);
            var modifyModel = new AppUserAddress();
            modifyModel.Modify(input.Name, input.Detail, tupleValue.Item1, tupleValue.Item2, tupleValue.Item3, input.Phone);
            var sign = await _appUserAddressRepository.UpdateAsync(d => modifyModel, d => d.IsDeleted == false && d.Id == input.AddressId && d.AppUserId == HttpWx.AppUserId);
            return Result(sign);
        }

        [HttpPost]
        public async Task<ApiResult> Delete([FromForm] int addressId)
        {
            var model = new AppUserAddress();
            model.SoftDelete();
            var sign = await _appUserAddressRepository.UpdateAsync(d => model, d => d.Id == addressId);
            return new ApiResult(sign);
        }

        [HttpPost]
        public async Task<ApiResult> SetIsDefault([FromForm] int addressId)
        {
            //把有默认地址的取消
            try
            {
                _db.Ado.BeginTran();
                var appUserAddress1 = new AppUserAddress(); appUserAddress1.SetDefaultAddress(false);
                var result1 = await _db.Updateable<AppUserAddress>().SetColumns(d => appUserAddress1).Where(d => d.IsDeleted && d.AppUserId == HttpWx.AppUserId).ExecuteCommandAsync();

                //设置当前新的默认地址
                var appUserAddress2 = new AppUserAddress(); appUserAddress1.SetDefaultAddress(true);
                var result2 = await _db.Updateable<AppUserAddress>().SetColumns(d => appUserAddress2).Where(d => d.IsDeleted && d.AppUserId == HttpWx.AppUserId && d.Id == addressId).ExecuteCommandAsync();
                if (result1 > 0 && result2 > 0)
                {
                    _db.Ado.CommitTran();
                }
            }
            catch
            {
                _db.Ado.RollbackTran();
                return new ApiResult("地址设置失败！");
            }
            return new ApiResult();
        }
    }
}